home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
500 MB Nyheder Direkte fra Internet 2
/
500 MB nyheder direkte fra internet CD 2.iso
/
start
/
data
/
text
/
variable.txt
< prev
next >
Wrap
Text File
|
1994-09-21
|
92KB
|
2,314 lines
WHAT'S A VARIABLE?
A letter can stand for a number. For example, X can stand for
the number 47, as in this program:
10 X=47
20 PRINT X+2
Line 10 says X stands for the number 47. In other words, X is a
name for the number 47.
Line 20 says to print X+2. Since X is 47, X+2 is 49; so the
computer will print 49. That's the only number the computer will
print; it will not print 47.
Jargon
A letter that stands for a number is called a numeric variable.
In that program, X is a numeric variable; it stands for the
number 47. The value of X is 47. Line 10 is called an assignment
statement, because it assigns 47 to X.
More examples
Here's another example:
10 Y=38
20 PRINT Y-2
Line 10 says Y is a numeric variable that stands for the number
38.
Line 20 says to print Y-2. Since Y is 38, Y-2 is 36; so the
computer will print 36.
Example:
10 B=8
20 PRINT B*3
Line 10 says B is 8. Line 20 says to print B*3, which is 8*3,
which is 24; so the computer will print 24.
One variable can define another:
10 M=6
20 P=M+1
30 PRINT M*P
Line 10 says M is 6. Line 20 says P is M+1, which is 6+1, which
is 7; so P is 7. Line 30 says to print M*P, which is 6*7, which
is 42; so the computer will print 42.
A value can change:
10 F=4
20 F=9
30 PRINT F*2
Line 10 says F's value is 4. Line 20 changes F's value to 9, so
line 30 prints 18.
Hassles
On the left side of the
equal sign, you must have one variable:
Allowed Not allowed
Not allowed
P=M+1 P-M=1
1=P-M
one variable two variables
not a variable
The variable on the left
side of the equation is the only one that changes. For example,
the statement P=M+1 changes the value of P but not M. The
statement A=B changes the value of A but not B:
10 A=1
20 B=7
30 A=B
40 PRINT A+B
Line 30 changes A, to make it equal B; so A becomes 7. Since both
A and B are now 7, line 40 prints 14.
``A=B'' versus ``B=A''
Saying ``A=B'' has a different effect from ``B=A''. That's
because ``A=B'' changes the value of A (but not B); ``B=A''
changes the value of B (but not A).
Compare these programs:
10 A=1 10 A=1
20 B=7 20 B=7
30 A=B 30 B=A
40 PRINT A+B 40 PRINT A+B
In the left program
(which you saw before), line 30 changes A to 7, so both A and B
are 7. Line 40 prints 14.
In the right program,
line 30 changes B to 1, so both A and B are 1. Line 40 prints 2.
A variable is a box
If variables ever confuse you, think of a variable as being a
box. Here's how. . . .
The computer's random-access memory (RAM) consists of
electronic boxes. This program puts a number into a box:
10 X=47
20 PRINT X+2
Line 10 puts 47 into box X, like this:
┌─────────────┐
Box X │ 47 │
└─────────────┘
Line 20 says to print what's in box X, plus 2. So the computer
will print 49.
You can change what's in a box:
10 F=4
20 F=9
30 PRINT F*2
Line 10 puts 4 into box F:
┌─────────────┐
Box F │ 4 │
└─────────────┘
Line 20 puts 9 into box F; the 9 replaces the 4:
┌─────────────┐
Box F │ 9 │
└─────────────┘
Line 30 prints 18.
To see why ``A=B'' has a different effect from ``B=A'', compare
these programs again:
10 A=1 10 A=1
20 B=7 20 B=7
30 A=B 30 B=A
40 PRINT A+B 40 PRINT A+B
In both programs, lines 10 and 20 do this:
┌─────────────┐
Box A │ 1 │
└─────────────┘
┌─────────────┐
Box B │ 7 │
└─────────────┘
In the left program, line 30 makes the number in box A become 7
(so both boxes contain 7, and line 40 prints 14). In the right
program, line 30 makes the number in box B become 1 (so both
boxes contain 1, and line 40 prints 2).
When to use variables
Here's a practical example of when
to use variables.
Suppose you're selling something
that costs $1297.43, and you want to do these calculations:
multiply $1297.43 by 2
multiply $1297.43 by .05
add $1297.43 to $483.19
divide $1297.43 by 37
subtract $1297.43 from $8598.61
multiply $1297.43 by 28.7
To do those six calculations, you
could run this program:
10 PRINT 1297.43*2; 1297.43*.05; 1297.43+483.19; 1297.43/37;
8598.61-1297.43
20 PRINT 1297.43*28.7
But that program's silly, since it contains the number 1297.43
six times. This program's briefer, because it uses a variable:
10 C=1297.43
20 PRINT C*2; C*.05; C+483.19; C/37; 8598.61-C; C*28.7
So whenever you need to use a number
several times, turn the number into a variable, which will make
your program briefer.
String variables
A string is any collection of
characters, such as ``I LOVE YOU''. Each string must be in
quotation marks.
A letter can stand for a string ___
if you put a dollar sign after the letter, like this:
10 G$="DOWN"
20 PRINT G$
Line 10 says G$ stands for the
string ``DOWN''. Line 20 prints:
DOWN
In that program, G$ is a variable.
Since it stands for a string, it's called a string variable.
Every string variable must end with
a dollar sign. The dollar sign is supposed to remind you of a
fancy S, which stands for String. Line 10 is pronounced, ``G
String is DOWN''.
If you're paranoid, you'll love this
program:
10 L$="THEY'RE LAUGHING AT YOU"
20 PRINT L$
30 PRINT L$
40 PRINT L$
Line 10 says L$ stands for the string ``THEY'RE LAUGHING AT
YOU''. Lines 20, 30, and 40 make the computer print:
THEY'RE LAUGHING AT YOU
THEY'RE LAUGHING AT YOU
THEY'RE LAUGHING AT YOU
Nursery rhymes
The computer can recite nursery
rhymes:
10 P$="PEAS PORRIDGE"
20 PRINT P$;" HOT"
30 PRINT P$;" COLD"
40 PRINT P$;" IN THE POT"
50 PRINT "NINE DAYS OLD"
Line 10 says P$ stands for ``PEAS
PORRIDGE''. Lines 20-50 make the computer print:
PEAS PORRIDGE HOT
PEAS PORRIDGE COLD
PEAS PORRIDGE IN THE POT
NINE DAYS OLD
This program prints a fancier rhyme:
10 H$="HICKORY, DICKORY, DOCK!"
20 M$="THE MOUSE (SQUEAK! SQUEAK!)"
30 C$="THE CLOCK (TICK! TOCK!)"
40 PRINT H$
50 PRINT M$;" RAN UP ";C$
60 PRINT C$;" STRUCK ONE"
70 PRINT M$;" RAN DOWN"
80 PRINT H$
Lines 10-30 define H$, M$, and C$. Lines 40-80 make the computer
print:
HICKORY, DICKORY, DOCK!
THE MOUSE (SQUEAK! SQUEAK!) RAN UP THE CLOCK (TICK! TOCK!)
THE CLOCK (TICK! TOCK!) STRUCK ONE
THE MOUSE (SQUEAK! SQUEAK!) RAN DOWN
HICKORY, DICKORY, DOCK!
Undefined variables
If you don't define a numeric variable, the computer assumes
it's zero:
10 PRINT R
Since R hasn't been defined, line 10 prints zero.
The computer doesn't look ahead:
10 PRINT J
20 J=5
When the computer encounters line 10, it doesn't look ahead to
find out what J is. As of line 10, J is still undefined, so the
computer prints zero.
If you don't define a string variable, the computer assumes
it's blank:
10 PRINT F$
Since F$ hasn't been defined, line 10 makes the computer print a
line that says nothing; the line the computer prints is blank.
Long variable names
A numeric variable's name can be a letter (such as X) or a
longer combination of characters, such as:
PROFIT.IN.1989.BEFORE.NOVEMBER.PROMOTION
For example, you can type:
10 PROFIT.IN.1989.BEFORE.NOVEMBER.PROMOTION = 3497.18
20 PROFIT.IN.1989 = PROFIT.IN.1989.BEFORE.NOVEMBER.PROMOTION +
6214.27
30 PRINT PROFIT.IN.1989
The computer will print:
9711.45
The variable's name can be quite long: up to 40 characters!
The first character in the name must be a letter. The remaining
characters can be letters, digits, or periods.
The name must not be a word that has a special meaning to the
computer. For example, the name cannot be PRINT.
If the variable stands for a string, the name can have up to 40
characters, followed by a dollar sign, making a total of 41
characters, like this:
MY.JOB.IN.1989.BEFORE.NOVEMBER.PROMOTION$
Although modern computers permit long variable names, primitive
computers don't. To find out whether your computer permits long
variable names, check the ``Versions of BASIC'' appendix.
Professional programmers use long variable names, because long
names make the programs easier to understand.
I'll avoid long names since some computers don't permit them;
but if your computer permits them, use them!
INPUT
Humans ask questions; so to turn the computer into a human, you
must make it ask questions too. To make the computer ask a
question, use the word INPUT.
This program makes the computer ask for your name:
10 INPUT "WHAT IS YOUR NAME";N$
20 PRINT "I ADORE ANYONE WHOSE NAME IS ";N$
When the computer sees line 10, the computer asks ``WHAT IS
YOUR NAME?'' and then waits for you to answer the question. Your
answer will be called N$. For example, if you answer MARIA, then
N$ is MARIA. Line 20 makes the computer print:
I ADORE ANYONE WHOSE NAME IS MARIA
Here's the whole conversation; I've underlined the parts typed
by you. . . .
You tell the computer to run:RUN
The computer asks for your name:WHAT IS YOUR NAME? MARIA
The computer praises your name:I ADORE ANYONE WHOSE NAME IS MARIA
Try that example. Be careful! When you type line 10, which says
INPUT, make sure you type the two quotation marks and the
semicolon. You don't have to type a question mark: when the
computer runs your program, it will automatically put a question
mark at the end of the question.
Just for fun, run that program again and pretend you're
somebody else. . . .
You tell the computer to run:RUN
The computer asks for your name:WHAT IS YOUR NAME? BUD
The computer praises your name:I ADORE ANYONE WHOSE NAME IS BUD
When the computer asks for your name, if you say something
weird, the computer will give you a weird reply. . . .
Make the computer run:RUN
Computer asks your name:WHAT IS YOUR NAME? NONE OF YOUR
BUSINESS!!!
The computer replies:I ADORE ANYONE WHOSE NAME IS NONE OF YOUR
BUSINESS!!!
College admissions
This program prints a letter, admitting you to the college of
your choice:
10 INPUT "WHAT COLLEGE WOULD YOU LIKE TO ENTER";C$
20 PRINT "CONGRATULATIONS!"
30 PRINT "YOU HAVE JUST BEEN ADMITTED TO ";C$
40 PRINT "IT FITS YOUR PERSONALITY"
50 PRINT "I HOPE YOU GO TO ";C$
60 PRINT " RESPECTFULLY YOURS"
70 PRINT " THE DEAN OF ADMISSIONS"
When the computer sees line 10, the computer asks ``WHAT
COLLEGE WOULD YOU LIKE TO ENTER?'' and waits for you to answer.
Your answer will be called C$. If you'd like to be admitted to
HARVARD, you'll be pleased. . . .
You tell the computer to run:RUN
The computer asks:WHAT COLLEGE WOULD YOU LIKE TO ENTER? HARVARD
The computer admits you:CONGRATULATIONS!
YOU HAVE JUST BEEN ADMITTED TO HARVARD
IT FITS YOUR PERSONALITY
I HOPE YOU GO TO HARVARD
RESPECTFULLY YOURS
THE DEAN OF ADMISSIONS
You can choose any college you wish:
RUN
WHAT COLLEGE WOULD YOU LIKE TO ENTER? HELL
CONGRATULATIONS!
YOU HAVE JUST BEEN ADMITTED TO HELL
IT FITS YOUR PERSONALITY
I HOPE YOU GO TO HELL
RESPECTFULLY YOURS
THE DEAN OF ADMISSIONS
That program
consists of three parts:
1. The
computer begins by asking you a question (``What college would
you like to enter?''). The computer's question is called the
prompt, because it prompts you to answer.
2. Your
answer (the college's name) is called your input, because it's
information that you're putting into the computer.
3. The
computer's reply (the admission letter) is called the computer's
output, because it's the final answer that the computer puts out.
INPUT versus PRINT
The word
INPUT is the opposite of the word PRINT.
The word
PRINT makes the computer print information out. The word INPUT
makes the computer take information in.
What the
computer prints out is called the output. What the computer takes
in is called your input.
Input and
Output are collectively called I/O, so the INPUT and PRINT
statements are called I/O statements.
Once upon a time
Let's make the computer write a story, by filling in the
blanks:
ONCE UPON A TIME, THERE WAS A YOUNGSTER NAMED _____________
your name
WHO HAD A FRIEND NAMED _________________
friend's name
_____________ WANTED TO ________________________
_________________
your name verb (such as "pat") friend's name
BUT _________________ DIDN'T WANT TO ________________________
_____________
friend's name verb (such as "pat")
your name
WILL _____________ _______________________ _________________
your name verb (such as "pat") friend's name
WILL _________________ ________________________ _____________
friend's name verb (such as "pat") your name
TO FIND OUT, COME BACK AND SEE THE NEXT EXCITING EPISODE
OF _____________ AND _________________
your name friend's name
To write the story, the computer must ask for your name, your
friend's name, and a verb. To make the computer ask, your program
must say INPUT:
10 INPUT "WHAT IS YOUR NAME";Y$
20 INPUT "WHAT'S YOUR FRIEND'S NAME";F$
30 INPUT "IN 1 WORD, SAY SOMETHING YOU CAN DO TO YOUR FRIEND";V$
Then make the computer print the story:
40 PRINT "HERE'S MY STORY...."
50 PRINT "ONCE UPON A TIME, THERE WAS A YOUNGSTER NAMED ";Y$
60 PRINT "WHO HAD A FRIEND NAMED ";F$
70 PRINT Y$;" WANTED TO ";V$;" ";F$
80 PRINT "BUT ";F$;" DIDN'T WANT TO ";V$;" ";Y$
90 PRINT "WILL ";Y$;" ";V$;" ";F$
100 PRINT "WILL ";F$;" ";V$;" ";Y$
110 PRINT "TO FIND OUT, COME BACK AND SEE THE NEXT EXCITING
EPISODE"
120 PRINT "OF ";Y$;" AND ";F$
Here's a sample run:
WHAT'S YOUR NAME? DRACULA
WHAT'S YOUR FRIEND'S NAME? MARILYN MONROE
IN 1 WORD, SAY SOMETHING YOU CAN DO TO YOUR FRIEND? BITE
HERE'S MY STORY....
ONCE UPON A TIME, THERE WAS A YOUNGSTER NAMED DRACULA
WHO HAD A FRIEND NAMED MARILYN MONROE
DRACULA WANTED TO BITE MARILYN MONROE
BUT MARILYN MONROE DIDN'T WANT TO BITE DRACULA
WILL DRACULA BITE MARILYN MONROE
WILL MARILYN MONROE BITE DRACULA
TO FIND OUT, COME BACK AND SEE THE NEXT EXCITING EPISODE
OF DRACULA AND MARILYN MONROE
Here's another run:
WHAT'S YOUR NAME? SUPERMAN
WHAT'S YOUR FRIEND'S NAME? KING KONG
IN 1 WORD, SAY SOMETHING YOU CAN DO TO YOUR FRIEND? TICKLE
HERE'S MY STORY....
ONCE UPON A TIME, THERE WAS A YOUNGSTER NAMED SUPERMAN
WHO HAD A FRIEND NAMED KING KONG
SUPERMAN WANTED TO TICKLE KING KONG
BUT KING KONG DIDN'T WANT TO TICKLE SUPERMAN
WILL SUPERMAN TICKLE KING KONG
WILL KING KONG TICKLE SUPERMAN
TO FIND OUT, COME BACK AND SEE THE NEXT EXCITING EPISODE
OF SUPERMAN AND KING KONG
Try it: put in your own name, the name of your friend, and
something you'd like to do to your friend.
Contest
This program prints a certificate saying you won a contest:
10 INPUT "WHAT'S YOUR NAME";Y$
20 INPUT "WHAT'S YOUR FRIEND'S NAME";F$
30 INPUT "WHAT'S THE NAME OF ANOTHER FRIEND";A$
40 INPUT "NAME A COLOR";C$
50 INPUT "NAME A PLACE";P$
60 INPUT "NAME A FOOD";D$
70 INPUT "NAME AN OBJECT";J$
80 INPUT "NAME A PART OF THE BODY";B$
90 INPUT "NAME A STYLE OF COOKING (SUCH AS BAKED OR FRIED)";S$
100 PRINT
110 PRINT "CONGRATULATIONS ";Y$
120 PRINT "YOU'VE WON THE BEAUTY CONTEST, BECAUSE OF YOUR
GORGEOUS ";B$
130 PRINT "YOUR PRIZE IS A ";C$;" ";J$
140 PRINT "PLUS A TRIP TO ";P$;" WITH YOUR FRIEND ";F$
150 PRINT "PLUS...AND THIS IS THE BEST PART OF ALL..."
160 PRINT "DINNER FOR THE TWO OF YOU AT ";A$;"'S NEW RESTAURANT"
170 PRINT "WHERE ";A$;" WILL GIVE YOU ALL THE ";S$;" ";D$;" YOU
CAN EAT"
180 PRINT "CONGRATULATIONS ";Y$;"...TODAY'S YOUR LUCKY DAY..."
190 PRINT "NOW EVERYBODY WANTS TO KISS YOUR AWARD-WINNING ";B$
Here's a sample run:
WHAT'S YOUR NAME? LONG JOHN SILVER
WHAT'S YOUR FRIEND'S NAME? THE PARROT
WHAT'S THE NAME OF ANOTHER FRIEND? JIM
NAME A COLOR? GOLD
NAME A PLACE? TREASURE ISLAND
NAME A FOOD? RUM-SOAKED COCONUTS
NAME AN OBJECT? CHEST OF JEWELS
NAME A PART OF THE BODY? MISSING LEG
NAME A STYLE OF COOKING (SUCH AS BAKED OR FRIED)? BARBECUED
CONGRATULATIONS LONG JOHN SILVER
YOU'VE WON THE BEAUTY CONTEST, BECAUSE OF YOUR GORGEOUS MISSING
LEG
YOUR PRIZE IS A GOLD CHEST OF JEWELS
PLUS A TRIP TO TREASURE ISLAND WITH YOUR FRIEND THE PARROT
PLUS...AND THIS IS THE BEST PART OF ALL...
DINNER FOR THE TWO OF YOU AT JIM'S NEW RESTAURANT
WHERE JIM WILL GIVE YOU ALL THE BARBECUED RUM-SOAKED COCONUTS YOU
CAN EAT
CONGRATULATIONS LONG JOHN SILVER...TODAY'S YOUR LUCKY DAY...
NOW EVERYBODY WANTS TO KISS YOUR AWARD-WINNING MISSING LEG
This run describes the contest that brought Ronald Reagan to
the White House:
WHAT'S YOUR NAME? RONNIE REAGAN
WHAT'S YOUR FRIEND'S NAME? NANCY
WHAT'S THE NAME OF ANOTHER FRIEND? ALICE
NAME A COLOR? RED-WHITE-AND-BLUE
NAME A PLACE? THE WHITE HOUSE
NAME A FOOD? JELLY BEANS
NAME AN OBJECT? COWBOY HAT
NAME A PART OF THE BODY? CHEEKS
NAME A STYLE OF COOKING (SUCH AS BAKED OR FRIED)? STEAMED
CONGRATULATIONS RONNIE REAGAN
YOU'VE WON THE BEAUTY CONTEST, BECAUSE OF YOUR GORGEOUS CHEEKS
YOUR PRIZE IS A RED-WHITE-AND-BLUE COWBOY HAT
PLUS A TRIP TO THE WHITE HOUSE WITH YOUR FRIEND NANCY
PLUS...AND THIS IS THE BEST PART OF ALL...
DINNER FOR THE TWO OF YOU AT ALICE'S NEW RESTAURANT
WHERE ALICE WILL GIVE YOU ALL THE STEAMED JELLY BEANS YOU CAN EAT
CONGRATULATIONS RONNIE REAGAN...TODAY'S YOUR LUCKY DAY...
NOW EVERYBODY WANTS TO KISS YOUR AWARD-WINNING CHEEKS
Bills
If you're a nasty bill collector, you'll love this program:
10 INPUT "WHAT IS THE CUSTOMER'S FIRST NAME";F$
20 INPUT "LAST NAME";L$
30 INPUT "STREET ADDRESS";A$
40 INPUT "CITY";C$
50 INPUT "STATE";S$
60 INPUT "ZIP CODE";Z$
70 PRINT
80 PRINT F$;" ";L$
90 PRINT A$
100 PRINT C$;" ";S$;" ";Z$
110 PRINT
120 PRINT "DEAR ";F$;","
130 PRINT " YOU STILL HAVEN'T PAID THE BILL."
140 PRINT "IF YOU DON'T PAY IT SOON, ";F$;","
150 PRINT "I'LL COME VISIT YOU IN ";C$
160 PRINT "AND PERSONALLY SHOOT YOU."
170 PRINT " YOURS TRULY,"
180 PRINT " SURE-AS-SHOOTIN'"
190 PRINT " YOUR CRAZY CREDITOR"
Can you figure out what that program does?
Numeric input
This program makes the computer predict your future:
10 PRINT "I PREDICT WHAT'LL HAPPEN TO YOU IN THE YEAR 2000!"
20 INPUT "IN WHAT YEAR WERE YOU BORN";Y
30 PRINT "IN THE YEAR 2000, YOU'LL TURN";2000-Y;"YEARS OLD."
Here's a sample run:
I PREDICT WHAT'LL HAPPEN TO YOU IN THE YEAR 2000!
IN WHAT YEAR WERE YOU BORN? 1962
IN THE YEAR 2000, YOU'LL TURN 38 YEARS OLD.
Suppose you're selling tickets to a play. Each ticket costs
$2.79. (You decided $2.79 would be a nifty price, because the
cast has 279 people.) This program finds the price of multiple
tickets:
10 INPUT "HOW MANY TICKETS";T
20 PRINT "THE TOTAL PRICE IS $";T*2.79
This program tells you how much the ``energy crisis'' costs
you, when you drive your car:
10 INPUT "HOW MANY MILES DO YOU WANT TO DRIVE";M
20 INPUT "HOW MANY PENNIES DOES A GALLON OF GAS COST";P
30 INPUT "HOW MANY MILES-PER-GALLON DOES YOUR CAR GET";R
40 PRINT "THE GAS FOR YOUR TRIP WILL COST YOU $";M*P/(R*100)
Here's a sample run:
HOW MANY MILES DO YOU WANT TO DRIVE? 400
HOW MANY PENNIES DOES A GALLON OF GAS COST? 95.9
HOW MANY MILES-PER-GALLON DOES YOUR CAR GET? 31
THE GAS FOR YOUR TRIP WILL COST YOU $ 12.3742
Conversion
This program converts
feet to inches:
10 INPUT "HOW MANY FEET";F
20 PRINT F;"FEET =";F*12;"INCHES"
Here's a sample run:
HOW MANY FEET? 3
3 FEET = 36 INCHES
Trying to convert to the
metric system? This program converts inches to centimeters:
10 INPUT "HOW MANY INCHES";I
20 PRINT I;"INCHES =";I*2.54;"CENTIMETERS"
Nice day today, isn't
it? This program converts the temperature from Celsius to
Fahrenheit:
10 INPUT "HOW MANY DEGREES CELSIUS";C
20 PRINT C;"DEGREES CELSIUS =";C*1.8+32;"DEGREES FAHRENHEIT"
Here's a sample run:
HOW MANY DEGREES CELSIUS? 20
20 DEGREES CELSIUS = 68 DEGREES FAHRENHEIT
See, you can write the
Guide yourself! Just hunt through any old math or science book,
find any old formula (such as F=C*1.8+32), and turn it into a
program.
IF . . . THEN
The computer understands the words IF and THEN.
Therapist
Let's turn your computer into a therapist.
To make the computer ask the patient, ``HOW ARE YOU?'', begin
the program like this:
10 INPUT "HOW ARE YOU";A$
That line makes the computer ask HOW ARE YOU and wait for the
patient's answer, which is called A$.
If the patient feels FINE, let's make the computer say THAT'S
GOOD. Here's how:
20 IF A$="FINE" THEN PRINT "THAT'S GOOD"
That line says that if the patient's answer (A$) is FINE, the
computer will print THAT'S GOOD.
If the patient feels LOUSY instead, let's make the computer say
TOO BAD. Here's how:
30 IF A$="LOUSY" THEN PRINT "TOO BAD"
Here's the entire program:
10 INPUT "HOW ARE YOU";A$
20 IF A$="FINE" THEN PRINT "THAT'S GOOD"
30 IF A$="LOUSY" THEN PRINT "TOO BAD"
When the patient types RUN, line 10 makes the computer ask HOW
ARE YOU and wait for the patient's answer, which is called A$. If
the patient's answer is FINE, line 20 makes the computer reply
THAT'S GOOD. If the patient's answer is LOUSY, line 30 makes the
computer reply TOO BAD.
Try running that program! Here's a sample run:
RUN
HOW ARE YOU? FINE
THAT'S GOOD
Here's another run:
RUN
HOW ARE YOU? LOUSY
TOO BAD
Underlying theory Whenever you say IF, you should also say
THEN. For example, line 20 (which says IF) also says THEN.
Similarly, line 30 (which says IF) says THEN.
Do not put a comma before THEN.
What comes between IF and THEN is called the condition. In line
20, the condition is:
A$="FINE"
If that condition is true (if A$ really does equal ``FINE''), the
computer does what comes after the word THEN, which is called the
consequence, which is:
PRINT "THAT'S GOOD"
Increase the computer's vocabulary In that program, what
happens if the patient says some word other than FINE or LOUSY?
For example, what happens if the patient says TERRIBLE? Since
the program doesn't tell the computer how to react to TERRIBLE,
the computer won't print any reaction at all. The computer will
do just what it always does at the end of a program: it will say
OK (or READY or a similar word).
Let's enhance the
program, so that if the patient says TERRIBLE, the computer will
say TOUGH TURKEY. Add the shaded line:
10 INPUT "HOW ARE YOU";A$
20 IF A$="FINE" THEN PRINT "THAT'S GOOD"
30 IF A$="LOUSY" THEN PRINT "TOO BAD"
40 IF A$="TERRIBLE" THEN PRINT "TOUGH TURKEY"
I feel the same way
Let's make the computer end the conversation by saying I FEEL THE
SAME WAY. Add the shaded line:
10 INPUT "HOW ARE YOU";A$
20 IF A$="FINE" THEN PRINT "THAT'S GOOD"
30 IF A$="LOUSY" THEN PRINT "TOO BAD"
40 IF A$="TERRIBLE" THEN PRINT "TOUGH TURKEY"
50 PRINT "I FEEL THE SAME WAY"
Since line 50 does not contain the word IF, the computer will
always print I FEEL THE SAME WAY at the end of the conversation,
regardless of what the patient says.
Here's a sample run:
RUN
HOW ARE YOU? FINE
THAT'S GOOD
I FEEL THE SAME WAY
Here's another:
RUN
HOW ARE YOU? TERRIBLE
TOUGH TURKEY
I FEEL THE SAME WAY
Another:
RUN
HOW ARE YOU? LONELY
I FEEL THE SAME WAY
Another:
RUN
HOW ARE YOU? I DON'T WANT TO TALK WITH YOU
I FEEL THE SAME WAY
Avoid monotony Having
the computer always say I FEEL THE SAME WAY is monotonous. To
make the program more interesting, let's make the computer say I
FEEL THE SAME WAY only if the patient doesn't say FINE, LOUSY, or
TERRIBLE. So if the patient says FINE, LOUSY, or TERRIBLE, let's
prevent the computer from saying I FEEL THE SAME WAY.
Whenever you want to
make the computer skip saying I FEEL THE SAME WAY, type the word
END, like this:
10 INPUT "HOW ARE YOU";A$
20 IF A$="FINE" THEN PRINT "THAT'S GOOD": END
30 IF A$="LOUSY" THEN PRINT "TOO BAD": END
40 IF A$="TERRIBLE" THEN PRINT "TOUGH TURKEY": END
50 PRINT "I FEEL THE SAME WAY"
In that program, if the patient types FINE, LOUSY, or TERRIBLE,
lines 20-40 make the computer print a two-word message and then
END, without printing I FEEL THE SAME WAY. The only way the
computer can reach line 50 (which prints I FEEL THE SAME WAY) is
if the patient avoids FINE, LOUSY, and TERRIBLE.
Here's a sample run:
RUN
HOW ARE YOU? FINE
THAT'S GOOD
Here's another:
RUN
HOW ARE YOU? LONELY
I FEEL THE SAME WAY
Charge $50 After the computer's given the patient therapy,
let's make the computer charge $50. Just add this line:
60 PRINT "I HOPE YOU ENJOYED YOUR THERAPY--NOW YOU OWE $50"
To make sure the computer always goes to that line and collects
the $50, regardless of what the patient says, replace each END by
GO TO 60. Altogether, the program looks like this:
10 INPUT "HOW ARE YOU";A$
20 IF A$="FINE" THEN PRINT "THAT'S GOOD": GO TO 60
30 IF A$="LOUSY" THEN PRINT "TOO BAD": GO TO 60
40 IF A$="TERRIBLE" THEN PRINT "TOUGH TURKEY": GO TO 60
50 PRINT "I FEEL THE SAME WAY"
60 PRINT "I HOPE YOU ENJOYED YOUR THERAPY--NOW YOU OWE $50"
Here's a sample run:
RUN
HOW ARE YOU? FINE
THAT'S GOOD
I HOPE YOU ENJOYED YOUR THERAPY--NOW YOU OWE $50
Here's another:
RUN
HOW ARE YOU? LONELY
I FEEL THE SAME WAY
I HOPE YOU ENJOYED YOUR THERAPY--NOW YOU OWE $50
In that program, try changing the strings to make the computer
print smarter remarks, become a better therapist, and charge even
more money.
Keywords
In that program, the only words the computer understands are
INPUT, IF, THEN, PRINT, GO, and TO. Those words are called
keywords.
Using just those keywords, you can write any program you wish!
Here's why. . . .
Can a computer become President? To become President of the
United States, you need four basic skills.
First, you must be a good talker, so you can give effective
speeches saying ``Vote for me!'', express your views, and make
folks do what you want.
But even if you're a good talker, you're useless unless you're
also a good listener. You must be able to listen to people's
needs and ask, ``What can I do to make you happy and get you to
vote for me?''
But even if you're a good talker and listener, you're still
useless unless you can make decisions. Should you give more money
to poor people? Should you bomb the enemy? Which actions should
you take, and under what conditions?
But even if you're a good talker and listener and decision
maker, you still need one more trait to become President: you
must be able to take the daily grind of politics. You must, again
and again, shake hands, make compromises, and raise funds. You
must have the patience to put up with the repetitive monotony of
those chores.
So altogether, to become President you need to be a good talker
and listener and decision maker and also have the patience to put
up with monotonous repetition.
Those are exactly the
four qualities the computer has! The word PRINT turns the
computer into a good speech-maker: by using the word PRINT, you
can make the computer write whatever speech you wish. The word
INPUT turns the computer into a good listener: by using the word
INPUT, you can make the computer ask humans lots of questions, to
find out who the humans are and what they want. The words IF and
THEN turn the computer into a decision maker: the computer can
analyze the IF condition, determine whether that condition is
true, and act accordingly. Finally, the words GO and TO enable
the computer to perform loops, which the computer will repeat
patiently.
So by using the words
PRINT, INPUT, IF THEN, and GO TO, you can make the computer
imitate any intellectual human activity. Those four magic phrases
___ PRINT, INPUT, IF THEN, and GO TO ___ are the only phrases you
need, to write whatever program you wish!
Yes, you can make the
computer imitate the President of the United States, do your
company's payroll, compose a beautiful poem, play a perfect game
of chess, contemplate the meaning of life, act as if it's falling
in love, or do whatever other intellectual or emotional task you
wish, by using just those four magic phrases. The only question
is: how? The Secret Guide to Computers teaches you how, by
showing you many examples of programs that do those remarkable
things.
What programmers believe
Yes, we programmers believe that all of life can be explained and
programmed. We believe all of life can be reduced to just those
four phrases: PRINT, INPUT, IF THEN, and GO TO. Programming is
the ultimate act of scientific reductionism: programmers reduce
all of life scientifically to just four phrases.
In addition to those
keywords (PRINT, INPUT, IF, THEN, GO, and TO), the computer
understands extra keywords also, such as END. Those extra
keywords aren't strictly necessary: if they hadn't been invented,
you could still write programs without them. But they make
programming easier.
A programmer is a person
who translates an ordinary English sentence (such as ``act like
the President'' or ``do the payroll'') into a series of BASIC
statements, using keywords such as PRINT, INPUT, IF THEN, GO TO,
and END.
The mysteries of life
Let's dig deeper into the mysteries of PRINT, INPUT, IF THEN, GO
TO, and the extra keywords. The deeper we dig, the more you'll
wonder: are you just a computer, made of flesh instead of wires?
Can everything that you do be explained in terms of PRINT, INPUT,
IF THEN, and GO TO?
By the time you finish
The Secret Guide to Computers, you'll know!
Mary Poppins meets Frankenstein
To make the computer interrogate a human, have the computer
ask:
ARE YOU MALE OR FEMALE?
If the human answers MALE, let's make the computer say:
SO IS FRANKENSTEIN
If the human answers FEMALE, let's make the computer say:
SO IS MARY POPPINS
Here's the program:
10 INPUT "ARE YOU MALE OR FEMALE";A$
20 IF A$="MALE" THEN PRINT "SO IS FRANKENSTEIN"
30 IF A$="FEMALE" THEN PRINT "SO IS MARY POPPINS"
Here's a sample run:
RUN
ARE YOU MALE OR FEMALE? MALE
SO IS FRANKENSTEIN
Here's another:
RUN
ARE YOU MALE OR FEMALE? FEMALE
SO IS MARY POPPINS
Neither MALE nor FEMALE? What does that program do if the human
says neither MALE nor FEMALE? What if the human says SUPER-MALE
or MACHO or NOT SURE or BOTH or YES? In those cases, the program
doesn't tell the computer how to reply, so the computer will make
no reply at all.
Let's improve the program, so that if the human says neither
MALE nor FEMALE the computer will reply ___
PLEASE SAY MALE OR FEMALE
ARE YOU MALE OR FEMALE?
and force the human to answer the question correctly.
To do that, add this line ___
40 PRINT "PLEASE SAY MALE OR FEMALE": GO TO 10
and put END at the end of lines 20 and 30, so the program looks
like this:
10 INPUT "ARE YOU MALE OR FEMALE";A$
20 IF A$="MALE" THEN PRINT "SO IS FRANKENSTEIN": END
30 IF A$="FEMALE" THEN PRINT "SO IS MARY POPPINS": END
40 PRINT "PLEASE SAY MALE OR FEMALE": GO TO 10
Line 10 makes the computer ask ``ARE YOU MALE OR FEMALE?'' and
wait for the human's answer, which is called A$. If the human's
answer is MALE, line 20 makes the computer print SO IS
FRANKENSTEIN and then end. If the human's answer is FEMALE, line
30 makes the computer print SO IS MARY POPPINS and then END. If
the human's answer is neither MALE nor FEMALE, the computer skips
over lines 20 and 30, so it comes to line 40, which makes it
print PLEASE SAY MALE OR FEMALE and then go back to line 10,
which forces the human to answer the question again.
Here's a sample run:
RUN
ARE YOU MALE OR FEMALE? MALE
SO IS FRANKENSTEIN
Here's another:
RUN
ARE YOU MALE OR FEMALE? FEMALE
SO IS MARY POPPINS
Another:
RUN
ARE YOU MALE OR FEMALE? MACHO
PLEASE SAY MALE OR FEMALE
ARE YOU MALE OR FEMALE? MALE
SO IS FRANKENSTEIN
Another:
RUN
ARE YOU MALE OR FEMALE? SUPER-MALE
PLEASE SAY MALE OR FEMALE
ARE YOU MALE OR FEMALE? NONE OF YOUR BUSINESS
PLEASE SAY MALE OR FEMALE
ARE YOU MALE OR FEMALE? MAIL
PLEASE SAY MALE OR FEMALE
ARE YOU MALE OR FEMALE? MALE
SO IS FRANKENSTEIN
In that program, if the
human makes a typing error and answers neither MALE nor FEMALE,
the computer arrives at line 40, which makes the computer gripe
and tell the human to try again. So the purpose of line 40 is to
react to errors. Line 40 is called an error-handling routine or
an error trap. That's because an error's like a vicious monster,
and line 40's purpose is to trap it.
Do you like Mary
Poppins? Let's extend the conversation. If the human says FEMALE,
let's make the computer say SO IS MARY POPPINS and then ask ``DO
YOU LIKE HER?'' If the human says YES, let's make the computer
say:
I LIKE HER TOO--SHE IS MY MOTHER
If the human says NO, let's make the computer say:
NEITHER DO I--SHE STILL OWES ME A DIME
If the human says neither YES nor NO, let's make the computer
say:
PLEASE SAY YES OR NO
DO YOU LIKE HER?
Here's the program:
10 INPUT "ARE YOU MALE OR FEMALE";A$
20 IF A$="MALE" THEN PRINT "SO IS FRANKENSTEIN": END
30 IF A$="FEMALE" THEN PRINT "SO IS MARY POPPINS": GO TO 100
40 PRINT "PLEASE SAY MALE OR FEMALE": GO TO 10
100 INPUT "DO YOU LIKE HER";B$
110 IF B$="YES" THEN PRINT "I LIKE HER TOO--SHE IS MY MOTHER ":
END
120 IF B$="NO" THEN PRINT "NEITHER DO I--SHE STILL OWES ME A
DIME": END
130 PRINT "PLEASE SAY YES OR NO": GO TO 100
Line 30 says: if the
human's answer is FEMALE, print SO IS MARY POPPINS and then go to
line 100, which asks ``DO YOU LIKE HER?'' Lines 110 and 120 make
the computer react to the human's opinion of Mary Poppins. Line
130 is like line 40: it's an error trap.
Weird programs
The computer's abilities are limited only by your own
imagination ___ and your weirdness. Here are some weird programs
from weird minds. . . .
Friends Like a human, the computer wants to meet new friends.
This program makes the computer show its true feelings:
10 INPUT "ARE YOU MY FRIEND";A$
20 IF A$="YES" THEN PRINT "THAT'S SWELL": END
30 IF A$="NO" THEN PRINT "GO JUMP IN A LAKE": END
40 PRINT "PLEASE SAY YES OR NO": GO TO 10
When you type RUN, the computer asks ``ARE YOU MY FRIEND?'' If
you say YES, the computer says THAT'S SWELL. If you say NO, the
computer says GO JUMP IN A LAKE.
Watch TV The most inventive programmers are kids. This program
was written by a girl in the sixth grade:
10 INPUT "CAN I COME OVER TO YOUR HOUSE TO WATCH T.V.";A$
20 IF A$="YES" THEN PRINT "THANKS. I'LL BE THERE AT 5 P.M.": END
30 IF A$="NO" THEN PRINT "HUMPH! YOUR FEET SMELL, ANYWAY.": END
40 PRINT "PLEASE SAY YES OR NO": GO TO 10
When you type RUN, the computer asks to watch your TV. If you say
YES, the computer promises to come to your house at 5. If you
refuse, the computer insults your feet.
Honesty Another sixth-grade girl wrote this program, to test
your honesty:
10 PRINT "FKGJDFGKJ*#K$JSLF*/#$()$&(IKJNHBGD52:?./KSDJK$E(EF$#/JI
K(*"
20 PRINT "FASDFJKL:JFRFVFJUNJI*&()JNE$#SKI#(!SERF HHW NNWAZ MAME
!!!"
30 PRINT "ZBB%%%%%##)))))FESDFJK DSFE N.D.JJUJASD EHWLKD******"
40 INPUT "DO YOU UNDERSTAND WHAT I SAID";A$
50 IF A$="NO" THEN PRINT "SORRY TO HAVE BOTHERED YOU": END
60 IF A$="YES" THEN GO TO 100
70 PRINT "PLEASE SAY YES OR NO": GO TO 10
100 PRINT "SSFJSLFKDJFL++++4567345677839XSDWFEGF/#$&**()---==!!ZZ
XX"
110 PRINT "###EDFHTG NVFDF MKJKF ==+--*$&% #RHFS SESD
DOPEKKKNJGFD DSBS"
120 INPUT "OKAY, WHAT DID I SAY";B$
130 PRINT "YOU ARE A LIAR, A LIAR, A BIG FAT LIAR!"
When you type RUN, lines 10-30 print nonsense. Then the
computer asks whether you understand that stuff. If you're honest
and answer NO, the computer will apologize. But if you pretend
that you understand the nonsense and answer YES, the computer
will print more nonsense, challenge you to translate it, wait for
you to fake a translation, and then scold you for lying.
Daddy's always right A Daddy wrote a program for his
five-year-old son, John.
When John runs the program and types his name, the computer
asks ``WHAT'S 2 AND 2?'' If John answers 4, the computer says NO,
2 AND 2 IS 22. If he runs the program again and answers 22, the
computer says NO, 2 AND 2 IS 4. No matter how many times he runs
the program and how he answers the question, the computer says
he's wrong. But when Daddy runs the program, the computer
replies, YES, DADDY IS ALWAYS RIGHT.
Here's how Daddy programmed the computer:
10 INPUT "WHAT'S YOUR NAME";N$
20 INPUT "WHAT'S 2 AND 2";A
30 IF N$="DADDY" THEN PRINT "YES, DADDY IS ALWAYS RIGHT": END
40 IF A=4 THEN PRINT "NO, 2 AND 2 IS 22": END
50 PRINT "NO, 2 AND 2 IS 4"
Fancy relations
You can make the IF clause very fancy:
IF clauseMeaning
IF A$="MALE"If A$ is ``MALE''
IF A=4 If A is 4
IF A<4 If A is less than 4
IF A>4 If A is greater than 4
IF A<=4 If A is less than or equal to 4
IF A>=4 If A is greater than or equal to 4
IF A<>4 If A is not 4
IF A$<"MALE"If A is a word that comes before ``MALE'' in the
dictionary
IF A$>"MALE"If A is a word that comes after ``MALE'' in the
dictionary
In the IF statement, the symbols =, <, >, <=, >=, and <> are
called relations.
When you write a relation, put the equal sign last:
RightWrong
<= =<
>= =>
To say ``not equal to'' say ``less than or greater than'', like
this: <>.
OR
The computer understands the word OR. For example, here's how
to say, ``If X is either 7 or 8, print the word WONDERFUL'':
IF X=7 OR X=8 THEN PRINT "WONDERFUL"
That example is composed of two conditions: the first condition
is ``X=7''; the second condition is ``X=8''. Those two conditions
combine, to form ``X=7 OR X=8'', which is called a compound
condition.
If you use the word OR, put it between two conditions.
Right:IF X=7 OR X=8 THEN PRINT "WONDERFUL"(``X=7'' and ``X=8''
are conditions.)
Wrong:IF X=7 OR 8 THEN PRINT "WONDERFUL"(``8'' is not a
condition.)
AND
The computer understands the word AND. Here's how to say, ``If
P is more than 5 and less than 10, print TUNA FISH'':
IF P>5 AND P<10 THEN PRINT "TUNA FISH"
Here's how to say, ``If S is at least 60 and less than 65, print
YOU ALMOST FAILED'':
IF S>=60 AND S<65 THEN PRINT "YOU ALMOST FAILED"
Here's how to say, ``If N is a number from 1 to 10, print THAT'S
GOOD'':
IF N>=1 AND N<=10 THEN PRINT "THAT'S GOOD"
ELSE
Here's how to say, ``If A is less than 18, print MINOR; but if
A is not less than 18, print ADULT'':
IF A<18 THEN PRINT "MINOR" ELSE PRINT "ADULT"
That line says to either PRINT ``MINOR'' or ELSE PRINT
``ADULT''. If A is less than 18, the computer will PRINT
``MINOR''; otherwise, the computer will PRINT ``ADULT''.
Here's how to say, ``If A is less than 18, print MINOR and
print YOUNG; if A is not less than 18, print ADULT and print
OLD'':
IF A<18 THEN PRINT "MINOR": PRINT "YOUNG" ELSE PRINT "ADULT":
PRINT "OLD"
Primitive computers don't understand the word ELSE. To find out
whether your computer is primitive, check the ``Versions of
BASIC'' appendix.
DATA . . . READ
Let's make the computer print this message:
I LOVE MEAT
I LOVE POTATOES
I LOVE LETTUCE
I LOVE TOMATOES
I LOVE BUTTER
I LOVE CHEESE
I LOVE ONIONS
I LOVE PEAS
That message concerns this list of food: MEAT, POTATOES,
LETTUCE, TOMATOES, BUTTER, CHEESE, ONIONS, PEAS. That list
doesn't change: the computer continues to love those foods
throughout the entire program.
A list that doesn't change is called data. So in the message
about food, the data is MEAT, POTATOES, LETTUCE, TOMATOES,
BUTTER, CHEESE, ONIONS, PEAS.
Whenever a problem involves data, put the data at the top of
the program, like this:
10 DATA MEAT,POTATOES,LETTUCE,TOMATOES,BUTTER,CHEESE,ONIONS,PEAS
You must tell the computer to READ the DATA:
20 READ A$
Line 20 makes the computer read the first datum (MEAT) and call
it A$. So A$ is MEAT.
Since A$ is MEAT, this line makes the computer print I LOVE
MEAT:
30 PRINT "I LOVE ";A$
Hooray! We made the computer handle the first datum correctly:
we made the computer print I LOVE MEAT. To make the computer
handle the rest of the data (POTATOES, LETTUCE, etc.), tell the
computer to READ the rest of the data: tell the computer to GO
back to the READ statement. Since the READ statement is line 20,
tell the computer to GO TO 20, like this:
40 GO TO 20
Line 40 makes the computer GO back TO line 20, which reads the
next datum (POTATOES).
Altogether, the program looks like this:
10 DATA MEAT,POTATOES,LETTUCE,TOMATOES,BUTTER,CHEESE,ONIONS,PEAS
20 READ A$
30 PRINT "I LOVE ";A$
40 GO TO 20
Lines 20-40 form a loop. Like most loops, the loop's bottom
line says GO TO. Since the loop's top line says READ, the loop is
called a READ loop. The computer goes round and round the loop.
Each time the computer comes to line 20, it reads another
datum. The first time it comes to line 20, it reads MEAT; the
next time, it reads POTATOES; the next time, it reads LETTUCE;
the next time, it reads TOMATOES; etc.
Line 30 makes the computer PRINT what it's read.
Altogether, the computer will print:
I LOVE MEAT
I LOVE POTATOES
I LOVE LETTUCE
I LOVE TOMATOES
I LOVE BUTTER
I LOVE CHEESE
I LOVE ONIONS
I LOVE PEAS
After the computer prints I LOVE PEAS, it comes to line 40 again,
which makes it go back to line 20, so the computer tries to read
even more data; but no more data remains! So the computer says:
OUT OF DATA
Then the computer stops.
Most
practical computer programs involve data (a list that doesn't
change). As a programmer, your job is to notice what the data is
and begin your program by saying DATA. After you type the data,
write the program's next line, which should say READ. Farther
down in your program, you should say GO TO so that you create
READ loop. Your program consists of two parts: the DATA and the
READ loop.
In the DATA
statement, you must put quotation marks around any string that
contains a comma or colon. For example, if one of the foods is
``HOT, JUICY, BIG, THICK, STEAKS'' (which contains commas), you
must put quotation marks around it.
Avoiding OUT OF DATA
When you run
that sample program about food, the last three lines the computer
prints are:
I LOVE ONIONS
I LOVE PEAS
OUT OF DATA
Instead of
saying OUT OF DATA, let's make the computer say ``I LOVE ALL
THOSE FOODS'', so that the last three lines look like this:
I LOVE ONIONS
I LOVE PEAS
I LOVE ALL THOSE FOODS
Here's how. . . .
Underneath
the data, say DATA END:
15 DATA END
When the computer reads the DATA END, make the computer say I
LOVE ALL THOSE FOODS and end:
20 READ A$: IF A$="END" THEN PRINT "I LOVE ALL THOSE FOODS": END
The DATA END underneath the data is called the end mark,
because it marks the data's end. The routine that says ___
IF A$="END" THEN PRINT "I LOVE ALL THOSE FOODS": END
is called the end routine, because the computer does that routine
at the end.
RESTORE
That program prints one copy of the computer's favorite foods.
If you want the computer to print many copies, change line 20 to
this:
20 READ A$: IF A$="END" THEN PRINT "I LOVE ALL THOSE FOODS":
RESTORE: GO TO 20
The word RESTORE tells the computer to go back to the beginning
of the data. The computer will print:
I LOVE MEAT
I LOVE POTATOES
I LOVE LETTUCE
I LOVE TOMATOES
I LOVE BUTTER
I LOVE CHEESE
I LOVE ONIONS
I LOVE PEAS
I LOVE ALL THOSE FOODS
I LOVE MEAT
I LOVE POTATOES
I LOVE LETTUCE
I LOVE TOMATOES
I LOVE BUTTER
I LOVE CHEESE
I LOVE ONIONS
I LOVE PEAS
I LOVE ALL THOSE FOODS
I LOVE MEAT
I LOVE POTATOES
etc.
The computer will print copies of what it likes again and again,
forever, unless you abort the program.
Henry the Eighth
Let's make the computer print this nursery rhyme:
I love ice cream
I love red
I love ocean
I love bed
I love tall grass
I love to wed
I love candles
I love divorce
I love my kingdom
I love my horse
I love you
Of course, of course,
For I am Henry the Eighth!
If you own a jump rope, have fun: try to recite that poem while
skipping rope!
This program makes the computer recite the poem repeatedly:
10 DATA ICE CREAM,RED,OCEAN,BED,TALL GRASS,TO WED
11 DATA CANDLES,DIVORCE,MY KINGDOM,MY HORSE,YOU
15 DATA END
20 READ A$: IF A$="END" THEN PRINT "OF COURSE, OF COURSE,": PRINT
"FOR I AM HENR
Y THE EIGHTH!": PRINT: RESTORE: GO TO 20
30 PRINT "I LOVE ";A$
35 IF A$="TO WED" THEN PRINT
40 GO TO 20
Since the data's too long to fit on a single line, I've put
part of the data in line 10 and the rest in line 11. Each line of
data must begin with the word DATA. In each line, put commas
between the items. Do not put a comma at the end of the line.
The program resembles the previous one. The only new line is
35, which makes the computer leave a blank line underneath ``TO
WED'', to mark the bottom of the first verse.
Party
Let's throw a party! To make the party yummy, let's ask each
guest to bring a kind of food that resembles the guest's name.
For example, let's have Sal bring salad, Russ bring Russian
dressing, Sue bring soup, Tom bring turkey, Winnie bring wine,
Kay bring cake, and Al bring Alka-Seltzer.
Let's send all those people invitations, in this form:
DEAR _____________
person's name
WE'RE THROWING A PARTY AT THE SECRET CLUBHOUSE TOMORROW AT
NOON!
PLEASE BRING ____
food
To make the computer print all the invitations, begin by
feeding the computer the DATA:
10 DATA SAL,SALAD,RUSS,RUSSIAN DRESSING,SUE,SOUP,TOM,TURKEY
20 DATA WINNIE,WINE,KAY,CAKE,AL,ALKA-SELTZER
The data comes in pairs; the first pair consists of SAL and
SALAD. Tell the computer to READ each pair of DATA:
30 READ P$,F$
Line 30 makes the computer read the first pair of data; so P$ is
the first person (SAL), and F$ is his food (SALAD).
These lines print the letter:
40 PRINT "DEAR ";P$
50 PRINT " WE'RE THROWING A PARTY AT THE SECRET CLUBHOUSE
TOMORROW AT NOON!"
60 PRINT "PLEASE BRING ";F$
At the end of the letter, leave two blank lines, to make room for
your signature:
70 PRINT
80 PRINT
Then complete the READ loop, by making the computer go back to
the beginning of the loop, to read the next pair:
90 GO TO 30
The computer will print a letter to each person, like this:
DEAR SAL
WE'RE THROWING A PARTY AT THE SECRET CLUBHOUSE TOMORROW AT
NOON!
PLEASE BRING SALAD
DEAR RUSS
WE'RE THROWING A PARTY AT THE SECRET CLUBHOUSE TOMORROW AT
NOON!
PLEASE BRING RUSSIAN DRESSING
etc.
After printing all the letters, the computer will say:
OUT OF DATA
Instead of saying OUT OF DATA, let's make the computer say:
I'VE FINISHED WRITING THE LETTERS
To do that, put END at the end of the data, twice ___
25 DATA END,END
and say what to do when the computer reaches the END:
30 READ P$,F$: IF P$="END" THEN PRINT "I'VE FINISHED WRITING THE
LETTERS": END
You need two ENDs at the end of the data, because the READ
statement says to read two strings (P$ and F$).
Debts
Suppose these people owe you things:
PersonWhat the person owes
Bob $537.29
Mike a dime
Sue 2 golf balls
Harry a steak dinner at Mario's
Mommy a kiss
Let's remind those people of their debt, by writing them
letters, in this form:
DEAR _____________
person's name
I JUST WANT TO REMIND YOU...
THAT YOU STILL OWE ME ____
debt
Begin with the DATA:
10 DATA BOB,$537.29,MIKE,A DIME,SUE,2 GOLF BALLS
20 DATA HARRY,A STEAK DINNER AT MARIO'S,MOMMY,A KISS
The data comes in pairs; the first pair consists of BOB and
$537.29. Tell the computer to READ each pair of DATA:
30 READ P$,D$
Line 30 makes the computer read the first pair of data; so P$ is
the first person (BOB), and D$ is his debt ($537.29).
Here's the rest of the program:
40 PRINT "DEAR ";P$
50 PRINT " I JUST WANT TO REMIND YOU..."
50 PRINT "THAT YOU STILL OWE ME ";D$
70 PRINT
80 PRINT
90 GO TO 30
The computer will print a letter to each person, like this:
DEAR BOB
I JUST WANT TO REMIND YOU...
THAT YOU STILL OWE ME $537.29
DEAR MIKE
I JUST WANT TO REMIND YOU...
THAT YOU STILL OWE ME A DIME
etc.
After printing all the letters, the computer will say:
OUT OF DATA
To prevent the computer from saying OUT OF DATA, add line 25
and retype line 30, as follows:
25 DATA END,END
30 READ P$,D$: IF P$="END" THEN PRINT "I'VE FINISHED WRITING THE
LETTERS": END
Diets
Suppose you're running a
diet clinic and get these results:
Person Weight beforeWeight
after
Joe 273 pounds219 pounds
Mary 412 pounds371 pounds
Bill 241 pounds173 pounds
Sam 309 pounds198 pounds
Here's how to make the computer print a nice report. . . .
Begin by feeding it the
DATA:
10 DATA JOE,273,219,MARY,412,371,BILL,241,173,SAM,309,198
The DATA comes in
triplets: the first triplet consists of JOE, 273, and 219. Tell
the computer to READ each triplet of DATA:
20 READ N$,B,A
That line makes the computer read the first triplet of data; so
N$ is the first person's name (JOE), B is his weight before
(273), and A is his weight after (219). Since B and A stand for
numbers instead of strings, they don't have any dollar signs.
These lines print the
report about him:
30 PRINT N$;" WEIGHED";B;"POUNDS BEFORE ATTENDING THE DIET C
LINIC"
40 PRINT "BUT WEIGHED JUST";A;"POUNDS AFTERWARDS"
50 PRINT "THAT'S A LOSS OF";B-A;"POUNDS"
At the end of that report about him, leave a blank line:
60 PRINT
Then complete the READ
loop, by making the computer go back to the loop's beginning:
70 GO TO 20
The computer will print:
JOE WEIGHED 273 POUNDS BEFORE ATTENDING THE DIET CLINIC
BUT WEIGHED JUST 219 POUNDS AFTERWARDS
THAT'S A LOSS OF 54 POUNDS
MARY WEIGHED 412 POUNDS BEFORE ATTENDING THE DIET CLINIC
BUT WEIGHED JUST 371 POUNDS AFTERWARDS
THAT'S A LOSS OF 41 POUNDS
etc.
At the end the computer
will say OUT OF DATA. Instead, let's make it say:
COME TO OUR DIET CLINIC!
To do that, put END and two zeros at the end of the data ___
15 DATA END,0,0
and say what to do when the computer reaches the END:
20 READ N$,B,A: IF N$="END" THEN PRINT "COME TO THE DIET CLI
NIC!": END
You need the two zeros after the END, because the READ statement
says to read two numbers (B and A) after the string N$. If you
omit the zeros, the computer will say OUT OF DATA. If you hate
zeros, you can use other numbers instead; but most programmers
prefer zeros.
French colors
Let's make the computer translate colors into French. For
example, if the human says RED, we'll make the computer say the
French equivalent, which is:
ROUGE
Altogether, a run will look like this:
RUN
WHICH COLOR INTERESTS YOU? RED
IN FRENCH, IT'S ROUGE
The program begins simply:
10 INPUT "WHICH COLOR INTERESTS YOU";C$
Next, we must make the computer translate the color into
French. To do so, feed the computer this English-French
dictionary:
EnglishFrench
white blanc
yellowjaune
orangeorange
red rouge
green vert
blue bleu
brown brun
black noir
That dictionary becomes the data:
20 DATA WHITE,BLANC,YELLOW,JAUNE,ORANGE,ORANGE,RED,ROUGE
30 DATA GREEN,VERT,BLUE,BLEU,BROWN,BRUN,BLACK,NOIR
The data comes in pairs; the first
pair consists of WHITE and BLANC. Tell the computer to READ each
pair of DATA:
40 READ E$,F$
That line makes the computer read the first pair of data; so E$
is the first English color (WHITE), and F$ is its French
equivalent (BLANC).
But that pair of data might be the
wrong pair. For example, if the human requested RED, the human
does not want the pair of WHITE and BLANC; instead, the human
wants the pair of RED and ROUGE. Tell the computer that if the
human's input (RED) doesn't match the English in the pair, go
read another pair:
50 IF E$<>C$ THEN GO TO 40
That line says: if E$ (which is the English in the data) is not
C$ (the color the human requested), go to 40 (which reads another
pair).
Lines 40 and 50 form a loop. The
computer goes round and round the loop, until it finds the pair
of data that matches the human's request. Since the loop's
purpose is to search for matching data, it's called a search
loop.
After the computer's found the
correct English-French pair, make the computer print the French:
60 PRINT "IN FRENCH, IT'S ";F$
Altogether, the program looks like
this. . . .
Ask the human: 10 INPUT "WHICH COLOR
INTERESTS YOU";C$
Use this dictionary: 20 DATA
WHITE,BLANC,YELLOW,JAUNE,ORANGE,ORANGE,RED,ROUGE
30 DATA
GREEN,VERT,BLUE,BLEU,BROWN,BRUN,BLACK,NOIR
Look at the dictionary: 40 READ E$,F$
If not found, try again: 50 IF E$<>C$ THEN GO TO 40
Print the French: 60 PRINT "IN FRENCH, IT'S
";F$
Here's a sample run:
RUN
WHICH COLOR INTERESTS YOU? RED
IN FRENCH, IT'S ROUGE
Here's another:
RUN
WHICH COLOR INTERESTS YOU? BROWN
IN FRENCH, IT'S BRUN
Here's another:
RUN
WHICH COLOR INTERESTS YOU? PINK
OUT OF DATA
The computer says OUT OF DATA because it can't find PINK in the
data.
Instead of saying OUT OF DATA, let's
make the computer say I WASN'T TAUGHT THAT COLOR. To do that, put
END at the end of the data; and when the computer reaches the
END, make the computer say I WASN'T TAUGHT THAT COLOR:
10 INPUT "WHICH COLOR INTERESTS YOU";C$
20 DATA WHITE,BLANC,YELLOW,JAUNE,ORANGE,ORANGE,RED,ROUGE
30 DATA GREEN,VERT,BLUE,BLEU,BROWN,BRUN,BLACK,NOIR
35 DATA END,END
40 READ E$,F$: IF E$="END" THEN PRINT "I WASN'T TAUGHT THAT
COLOR": END
50 IF E$<>C$ THEN GO TO 40
60 PRINT "IN FRENCH, IT'S ";F$
After line 60, the program just
ends. Instead of letting the computer end, let's make it
automatically rerun the program and translate another color. To
do that, say GO TO and RESTORE:
10 INPUT "WHICH COLOR INTERESTS YOU";C$
20 DATA WHITE,BLANC,YELLOW,JAUNE,ORANGE,ORANGE,RED,ROUGE
30 DATA GREEN,VERT,BLUE,BLEU,BROWN,BRUN,BLACK,NOIR,END,END
35 DATA END,END
40 READ E$,F$: IF E$="END" THEN PRINT "I WASN'T TAUGHT THAT
COLOR": GO TO 70
50 IF E$<>C$ THEN GO TO 40
60 PRINT "IN FRENCH, IT'S ";F$
70 RESTORE
80 GO TO 10
FOR . . . NEXT
Let's make the computer print every number from 1 to 100, like
this:
1
2
3
4
5
6
7
etc.
100
To do that, type this line ___
20 PRINT X
and also say that you want X to be every number from 1 to 100,
like this:
10 FOR X = 1 TO 100
20 PRINT X
Whenever you write a program that contains the word FOR, you
must say NEXT. So your program should look like this:
10 FOR X = 1 TO 100
20 PRINT X
30 NEXT X
That program works; it makes the computer print every number from
1 to 100.
Here's how it works. . . .
The computer begins at line 10, which says that you want X to
be every number from 1 to 100. So X starts at 1.
Then the computer comes to line 20, which says to print X; so
the computer prints:
1
Then the computer comes to line 30, which says to do the same
thing for the next X, and for the next X, and for the next X; so
the computer prints 2, and 3, and 4, and so on, all the way up to
100.
The computer prints many numbers, because the computer does
line 20 many times (once for each X).
The computer does line 20 many times, because line 20 is
between the words FOR and NEXT: it's underneath FOR, and above
NEXT. The computer repeats anything that's between the words FOR
and NEXT.
Most programmers get in the habit of indenting everything that
comes between the words FOR and NEXT; so in that program, I
indented the statement that says PRINT X. To make the
indentation, you can hit the SPACE bar repeatedly.
In line 30, if you're too lazy to type the X, you can omit it
and just type:
30 NEXT
When men meet women
Let's make the computer
print these lyrics:
I SAW 2 MEN
MEET 2 WOMEN
TRA-LA-LA!
I SAW 3 MEN
MEET 3 WOMEN
TRA-LA-LA!
I SAW 4 MEN
MEET 4 WOMEN
TRA-LA-LA!
I SAW 5 MEN
MEET 5 WOMEN
TRA-LA-LA!
THEY ALL HAD A PARTY!
HA-HA-HA!
To do that, type these
lines ___
The first line of each verse: 20 PRINT "I SAW";X;"MEN"
The second line of each verse: 30 PRINT "MEET";X;"WOMEN"
The third line of each verse: 40 PRINT "TRA-LA-LA!"
Blank line under each verse: 50 PRINT
and make X be every number from 2 up to 5:
10 FOR X = 2 TO 5
20 PRINT "I SAW";X;"MEN"
30 PRINT "MEET";X;"WOMEN"
40 PRINT "TRA-LA-LA!"
50 PRINT
60 NEXT
At the end of the song,
print the closing couplet:
10 FOR X = 2 TO 5
20 PRINT "I SAW";X;"MEN"
30 PRINT "MEET";X;"WOMEN"
40 PRINT "TRA-LA-LA!"
50 PRINT
60 NEXT
70 PRINT "THEY ALL HAD A PARTY!"
80 PRINT "HA-HA-HA!"
That program makes the computer print the entire song.
Here's an analysis:
10 FOR X =
2 TO 5
The computer will do the 20
PRINT "I SAW";X;"MEN"
indented lines repeatedly, 30
PRINT "MEET";X;"WOMEN"
for X=2, X=3, X=4, and X=5. 40
PRINT "TRA-LA-LA!"
50
PRINT
60 NEXT
Then the computer will 70 PRINT
"THEY ALL HAD A PARTY!"
print this couplet once. 80 PRINT
"HA-HA-HA!"
Since the computer does
lines 20-50 repeatedly, those lines form a loop. Here's the
general rule: the statements between FOR and NEXT form a loop.
The computer goes round and round the loop, for X=2, X=3, X=4,
and X=5. Altogether, it goes around the loop 4 times, which is a
finite number. Therefore, the loop is finite.
If you don't like the
letter X, choose a different letter. For example, you can choose
the letter I:
10 FOR I = 2 TO 5
20 PRINT "I SAW";I;"MEN"
30 PRINT "MEET";I;"WOMEN"
40 PRINT "TRA-LA-LA!"
50 PRINT
60 NEXT
70 PRINT "THEY ALL HAD A PARTY!"
80 PRINT "HA-HA-HA!"
When using the word FOR, most programmers prefer the letter I;
most programmers say ``FOR I'' instead of ``FOR X''. Saying ``FOR
I'' is an ``old tradition''. Following that tradition, the rest
of this book says ``FOR I'' (instead of ``FOR X''), except in
situations where some other letter feels more natural.
Squares
To find the square of a number, multiply the number by itself.
The square of 3 is ``3 times 3'', which is 9. The square of 4 is
``4 times 4'', which is 16.
Let's make the computer print the square of 3, 4, 5, etc., up
to 100, like this:
THE SQUARE OF 3 IS 9
THE SQUARE OF 4 IS 16
THE SQUARE OF 5 IS 25
THE SQUARE OF 6 IS 36
THE SQUARE OF 7 IS 49
etc.
THE SQUARE OF 100 IS 10000
To do that, type this line ___
20 PRINT "THE SQUARE OF";I;"IS";I*I
and make I be every number from 3 up to 100, like this:
10 FOR I = 3 TO 100
20 PRINT "THE SQUARE OF";I;"IS";I*I
30 NEXT
Secret meeting
This program prints 12 copies of the same message:
10 FOR I = 1 TO 12
20 PRINT "HUSH, HUSH!"
30 PRINT " WE'RE HAVING A SECRET MEETING..."
40 PRINT " IN THE COMPUTER ROOM..."
50 PRINT " TONIGHT..."
60 PRINT " AT 2 A.M."
70 PRINT " WEAR A FUNNY HAT."
80 PRINT
90 PRINT
100 NEXT
Lines 80 and 90 leave blank lines at the end of each copy for
your signature.
Midnight
This program makes the computer count to midnight:
10 FOR I = 1 TO 11
20 PRINT I
30 NEXT
40 PRINT "MIDNIGHT"
The computer will print:
1
2
3
4
5
6
7
8
9
10
11
MIDNIGHT
Let's put a semicolon at
the end of line 20:
10 FOR I = 1 TO 11
20 PRINT I;
30 NEXT
40 PRINT "MIDNIGHT"
The semicolon makes the computer print each item on the same
line, like this:
1 2 3 4 5 6 7 8 9 10 11 MIDNIGHT
If you want the computer
to press the ENTER key before MIDNIGHT, insert a PRINT line:
10 FOR I = 1 TO 11
20 PRINT I;
30 NEXT
35 PRINT
40 PRINT "MIDNIGHT"
Line 35 makes the computer press the ENTER key just before
MIDNIGHT, so the computer will print MIDNIGHT on a separate line,
like this:
1 2 3 4 5 6 7 8 9 10 11
MIDNIGHT
In line 20, the
semicolon means: do not press the ENTER key after I. Line 35
means: do press the ENTER key. So line 35 undoes line 20 and
makes the computer press the ENTER key before MIDNIGHT.
Let's make the computer
count to midnight 3 times, like this:
1 2 3 4 5 6 7 8 9 10 11
MIDNIGHT
1 2 3 4 5 6 7 8 9 10 11
MIDNIGHT
1 2 3 4 5 6 7 8 9 10 11
MIDNIGHT
To do that, put the entire program between the words FOR and
NEXT:
5 FOR A = 1 TO 3
10 FOR I = 1 TO 11
20 PRINT I;
30 NEXT
35 PRINT
40 PRINT "MIDNIGHT"
50 NEXT
That version contains a loop inside a loop: the loop that says
``FOR I'' is inside the loop that says ``FOR A''. The A loop is
called the outer loop; the I loop is called the inner loop. The
inner loop's variable must differ from the outer loop's. Since we
called the inner loop's variable ``I'', the outer loop's variable
must not be called ``I''; so I picked the letter A instead.
Programmers often think
of the outer loop as a bird's nest, and the inner loop as an egg
inside the nest. So programmers say the inner loop is nested in
the outer loop; the inner loop is a nested loop.
Favorite color
This program plays a guessing game:
10 PRINT "I'LL GIVE YOU FIVE GUESSES...."
20 FOR I = 1 TO 5
30 INPUT "WHAT'S MY FAVORITE COLOR";G$
40 IF G$="PINK" THEN GO TO 100
50 PRINT "NO."
60 NEXT
70 PRINT "SORRY, YOUR FIVE GUESSES ARE UP! YOU LOSE."
80 END
100 PRINT "CONGRATULATIONS! YOU DISCOVERED MY FAVORITE COLOR."
110 PRINT "IT TOOK YOU";I;"GUESSES".
Line 10 warns the human that only five guesses are allowed.
Line 20 makes the computer count from 1 to 5; to begin, I is 1.
Line 30 asks the human to guess the computer's favorite color;
the guess is called G$.
If the guess is PINK, the computer jumps from line 40 to line
100, prints CONGRATULATIONS, and tells how many guesses the human
took. But if the guess is not PINK, the computer proceeds from
line 40 to line 50, prints NO, and goes on to the next guess.
If the human guesses five times without success, the computer
proceeds from line 60 to line 70 and prints SORRY . . . YOU LOSE.
For example, if the human's third guess is PINK, the computer
prints:
CONGRATULATIONS! YOU DISCOVERED MY FAVORITE COLOR.
IT TOOK YOU 3 GUESSES.
If the human's very first guess is PINK, the computer prints:
CONGRATULATIONS! YOU DISCOVERED MY FAVORITE COLOR.
IT TOOK YOU 1 GUESSES.
Saying ``1 GUESSES'' is bad grammar but understandable.
Lines 20-60 form a loop. Line 20 says the loop will normally be
done five times. The line after the loop, line 70, is the loop's
normal exit. But if the human happens to input PINK, the computer
jumps out of the loop early, to line 100, which is the loop's
abnormal exit.
Finite pause
Have you ever met someone who acts romantic, then suddenly says
something cruel that breaks the romance?
Let's make the computer act that way. For example, let's make
the computer begin by crooning a romantic message:
10 PRINT "YOUR LUSCIOUS LIPS SMELL LIKE THE FINEST WINE"
Then let's make the computer pause, to give the human a chance
to admire that romantic message and make the human wait in
suspense for the next outburst of computer emotion. Here's how to
make the computer pause:
20 FOR I = 1 TO 7000: NEXT
That line makes the computer pause, while it counts up to 7000.
That line makes the computer mumble to itself, ``I is 1, I is 2,
I is 3, I is 4, . . . '' without printing anything on the screen.
While the computer is secretly and silently mumbling to itself up
to 7000, the human has a chance to read and admire the romantic
message printed by line 10.
Finally, let's make the computer analyze the meaning of lips
smelling like wine:
30 PRINT "YOU MUST BE DRUNK"
So altogether, that program makes the computer print YOUR
LUSCIOUS LIPS SMELL LIKE THE FINEST WINE, then pause, then say
YOU MUST BE DRUNK.
In that program, line 20 makes the computer pause, by making
the computer silently mumble up to 7000. The typical computer
mumbles 1000 times per second. Since line 20 says to mumble 7000
times, that line takes 7 seconds altogether, and so it makes the
computer pause for 7 seconds.
If you want the computer to pause for 12 seconds instead of 7,
retype line 20 so it says to mumble 12000 times instead of 7000.
Although the typical computer mumbles 1000 times per second,
your computer might mumble slightly faster or slower than that.
Try the program on your computer, and notice how many seconds
your computer pauses when doing 7000 mumbles. If your computer's
typical, it pauses 7 seconds; if your computer mumbles quickly,
it pauses less than 7 seconds; if your computer mumbles slowly,
it pauses more than 7 seconds.
Warning: your computer mumbles more slowly in long programs
than in short ones.
This program makes the computer print a famous joke:
10 PRINT "YOUR TEETH ARE LIKE STARS"
20 FOR I = 1 TO 7000: NEXT
30 PRINT "THEY COME OUT AT NIGHT"
Line 30 is the punch line. Line 20 makes the computer pause 7
seconds, before giving the punch line.
Experiment: invent your own joke, and make the computer pause
before printing the punch line.
Eye test This program makes the computer test how fast you can
read:
10 CLS
20 PRINT "IF YOU CAN READ THIS, YOU READ QUICKLY"
30 FOR I = 1 TO 250: NEXT
40 CLS
Line 10 makes the computer clear the screen, so that the entire
screen becomes blank. Line 20 makes the computer print:
IF YOU CAN READ THIS, YOU READ QUICKLY
Line 30 makes the computer pause for a quarter of a second (since
250 is a quarter of 1000). While the computer pauses, the message
stays on the screen. Line 40 erases the screen, so the message
stayed on the screen for just a quarter of a second. If you could
read the message in a quarter of a second, you have very quick
eyes!
I can't read that quickly. Can you? Try it! To make the eye
test easier, allow yourself longer than a quarter of a second to
read the message, by changing the 250 to a larger number.
Get together with your friends, and see how quickly they can
read. Flash different messages on the screen by changing line 20.
For example, try changing line 20 to this:
20 PRINT "MUMBLING MORONS MAKE MY MOM MISS MURDER MYSTERIES
MONDAY MORNING"
If your friends can read all that in a quarter of a second, they
probably belong in the Guinness Book of World Records.
To prevent your friends from cheating, make them close their
eyes while you're typing the program. When you've finished typing
the program, press the CLEAR key, so that the program becomes
invisible. Then tell your friends to open their eyes and type
RUN.
STEP
The FOR statement can be varied:
Statement Meaning
FOR I = 5 TO 17 STEP .1I will go from 5 to 17, counting by
tenths.
So I will be 5, then 5.1, then 5.2, etc., up to
17.
FOR I = 5 TO 17 STEP 3I will be every third number from 5 to 17.
So I will be 5, then 8, then 11, then 14, then
17.
FOR I = 17 TO 5 STEP -3I will be every third number from 17 down
to 5.
So I will be 17, then 14, then 11, then 8, then
5.
To count down, you must use the word STEP. To count from 17
down to 5, give this instruction:
FOR I = 17 TO 5 STEP -1
This program
prints a rocket countdown:
10 FOR I = 10 TO 1 STEP -1
20 PRINT I
30 NEXT
40 PRINT "BLAST OFF!"
The computer will print:
10
9
8
7
6
5
4
3
2
1
BLAST OFF!
This
statement is tricky:
FOR I = 5 TO 16 STEP 3
It says to start I at 5, and keep adding 3 until it gets past 16.
So I will be 5, then 8, then 11, then 14. I won't be 17, since 17
is past 16. The first value of I is 5; the last value is 14.
In the
statement FOR I = 5 TO 16 STEP 3, the first value or initial
value of I is 5, the limit value is 16, and the step size or
increment is 3. The I is called the counter or index or
loop-control variable. Although the limit value is 16, the last
value or terminal value is 14.
Programmers
usually say ``FOR I'', instead of ``FOR X'', because the letter I
reminds them of the word index.
VARIABLES & CONSTANTS
A numeric constant is a simple number, such as:
0 1 2 8 43.7 -524.6 .003
Another example of a numeric constant is 1.3E5, which means,
``take 1.3, and move its decimal point 5 places to the right''.
A numeric constant does not contain any arithmetic. For
example, since 7+1 contains arithmetic (+), it's not a numeric
constant. 8 is a numeric constant, even though 7+1 isn't.
A string constant is a simple string, in quotation marks:
"I LOVE YOU" "76 TROMBONES" "GO AWAY!!!" "XYPW
EXR///746"
A constant is a numeric constant or a string constant:
0 8 -524.6 1.3E5 "I LOVE YOU" "XYPW
EXR///746"
A variable is something that stands for something else. If it
stands for a string, it's called a string variable and ends with
a dollar sign, like this:
A$ B$ Y$ Z$
If the variable stands for a number, it's called a numeric
variable and lacks a dollar sign, like this:
A B Y Z
So all these are variables:
A$ B$ Y$ Z$ A B Y Z
Expressions
A numeric expression is a numeric constant (such as 8) or a
numeric variable (such as A) or a combination of them, such as
8+Z, or 8*A, or Z*A, or 8*2, or 7+1, or even
Z*A-(7+Z)/8+1.3E5*(-524.6+B).
A string expression is a string constant (such as ``I LOVE
YOU'') or a string variable (such as A$) or a combination.
An expression is a numeric expression or a string expression.
Statements
At the end of a GO TO statement, the line number must be a
numeric constant.
Right:50 GO TO 100 (100 is a numeric constant.)
Wrong:50 GO TO N (N is not a numeric constant.)
The INPUT statement's prompt must be a string constant:
Right:10 INPUT "WHAT IS YOUR NAME";N$(``WHAT IS YOUR NAME'' is a
constant.)
Wrong:10 INPUT Q$;N$ (Q$ is not a constant.)
In a DATA statement, you must have constants.
Right:10 DATA 8, 1.3E5 (8 and 1.3E5 are constants.)
Wrong:10 DATA 7+1, 1.3E5(7+1 is not a constant.)
In the DATA statement, if the constant is a string, you can omit
the quotation marks (unless the string contains a comma or a
colon).
Right:10 DATA "JOE","MARY"
Also right:10 DATA JOE,MARY
Here are the forms of the most popular BASIC statements:
General form Example
PRINT list of expressions PRINT "THE TEMPERATURE
IS";4+25;"DEGREES"
GO TO numeric constant GO TO 10
END END
STOP STOP
variable = expression X = 47+2
INPUT string constant ; variable INPUT "WHAT IS YOUR
NAME";N$
IF condition THEN list of statements IF A>=18 THEN PRINT "YOU":
PRINT "VOTE"
DATA list of constants DATA
JOE,273,219,MARY,412,371
READ list of variables READ N$,B,A
RESTORE RESTORE
FOR numeric variable = FOR I = 59+1 TO 100+N STEP
2+3
numeric expression TO
numeric expression STEP
numeric expression
NEXT numeric variable NEXT I
LOOP TECHNIQUES
Here's a strange program:
10 A=5
20 A=3+A
30 PRINT A
Line 20 means: the new A is 3 plus the old A. So the new A is
3+5, which is 8. Line 30 prints:
8
Let's look at that program more closely. Line 10 puts 5 into
box A:
When the computer sees line 20, it examines the equation's right
side and sees the 3+A. Since A is 5, the 3+A is 3+5, which is 8.
So line 20 says: A=8. The computer puts 8 into box A:
Line 30 prints 8.
Here's another weirdo:
10 B=6
20 B=B+1
30 PRINT B*2
Line 20 says the new B is ``the old B plus 1''. So the new B is
6+1, which is 7. Line 30 prints:
14
In that program, line 10 says B is 6; but line 20 increases B,
by adding 1 to B; so B becomes 7. Programmers say that B has been
increased or incremented. In line 20, the ``1'' is called the
increase or the increment.
The opposite of ``increment'' is decrement:
10 J=500
20 J=J-1
30 PRINT J
Line 10 says J starts at 500. But line 20 says the new J is ``the
old J minus 1'', so the new J is 500-1, which is 499. Line 30
prints:
499
In that program, J was decreased (or decremented). In line 20,
the ``1'' is called the decrease (or decrement).
Counting
Suppose you want the
computer to count, starting at 3, like this:
3
4
5
6
7
8
etc.
This program does it, by a special technique:
10 C=3
20 PRINT C
30 C=C+1
40 GO TO 20
In that program, C is
called the counter, because it helps the computer count.
Line 10 says C starts at
3. Line 20 makes the computer print C, so the computer prints:
3
Line 30 increases C by
adding 1 to it, so C becomes 4. Line 40 sends the computer back
to line 20, which prints the new value of C:
4
Then the computer comes
to line 30 again, which increases C again so C becomes 5. Line 40
sends the computer back to line 20 again, which prints:
5
The program's an
infinite loop: the computer will print 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, and so on, forever, unless you abort it.
General procedure Here's
the general procedure for making the computer count:
1. Start C at some value (such as 3).
2. Use C. (For example, tell the computer to PRINT C.)
3. Increase C, by saying C=C+1.
4. GO back TO step 2.
Variations To read the
printing more easily, put a semicolon at the end of the PRINT
statement:
10 C=3
20 PRINT C;
30 C=C+1
40 GO TO 20
The semicolon makes the computer print horizontally:
3 4 5 6 7 8 etc.
This program makes the
computer count, starting at 1:
10 C=1
20 PRINT C;
30 C=C+1
40 GO TO 20
The computer will print 1, 2, 3, 4, etc.
This program makes the
computer count, starting at 0:
10 C=0
20 PRINT C;
30 C=C+1
40 GO TO 20
The computer will print 0, 1, 2, 3, 4, etc.
Quiz
Let's make the computer give this quiz:
What's the capital of Nevada?
What's the chemical symbol for iron?
What word means 'brother or sister'?
What was Beethoven's first name?
How many cups are in a quart?
To make the computer score the quiz, we must tell it the
correct answers, which are:
Carson City
Fe
sibling
Ludwig
4
So the program contains this data:
10 DATA WHAT'S THE CAPITAL OF NEVADA,CARSON CITY
20 DATA WHAT'S THE CHEMICAL SYMBOL FOR IRON,FE
30 DATA WHAT WORD MEANS 'BROTHER OR SISTER',SIBLING
40 DATA WHAT WAS BEETHOVEN'S FIRST NAME,LUDWIG
50 DATA HOW MANY CUPS ARE IN A QUART,4
Tell the computer to READ the data:
100 READ Q$,A$
That line reads a pair of data: it reads a question (Q$) and the
correct answer (A$).
Make the computer ask the question and wait for the human's
response:
110 PRINT Q$;
120 INPUT "??";H$
Line 110 prints the question. Line 120 prints question marks
after the question, and waits for the human to respond; the
human's response is called H$.
Finally, evaluate the human's response. If the human's response
(H$) is the correct answer (A$), make the computer say
``CORRECT'' and GO TO the next question:
130 IF H$=A$ THEN PRINT "CORRECT": GO TO 100
But if the human's response is wrong, make the computer say
``NO'' and reveal the correct answer:
140 PRINT "NO, THE ANSWER IS: ";A$: GO TO 100
Here's a sample run:
RUN
WHAT'S THE CAPITAL OF NEVADA??? LAS VEGAS
NO, THE ANSWER IS: CARSON CITY
WHAT'S THE CHEMICAL SYMBOL FOR IRON??? FE
CORRECT
WHAT WORD MEANS 'BROTHER OR SISTER'??? I GIVE UP
NO, THE ANSWER IS: SIBLING
WHAT WAS BEETHOVEN'S FIRST NAME??? LUDVIG
NO, THE ANSWER IS: LUDWIG
HOW MANY CUPS ARE IN A QUART??? 4
CORRECT
OUT OF DATA
To give a quiz about different topics, change the data in lines
10-50.
Avoid OUT OF DATA Instead of making the computer say OUT OF
DATA, let's make it say:
I HOPE YOU ENJOYED THE QUIZ
To do that, write an end mark and an end routine:
60 DATA END,END
100 READ Q$,A$: IF Q$="END" THEN PRINT "I HOPE YOU ENJOYED T HE
QUIZ": END
Count the correct
answers Let's make the computer count how many questions the
human answered correctly. To do that, we need a counter. As
usual, let's call it C:
5 C=0
10 DATA WHAT'S THE CAPITAL OF NEVADA,CARSON CITY
20 DATA WHAT'S THE CHEMICAL SYMBOL FOR IRON,FE
30 DATA WHAT WORD MEANS 'BROTHER OR SISTER',SIBLING
40 DATA WHAT WAS BEETHOVEN'S FIRST NAME,LUDWIG
50 DATA HOW MANY CUPS ARE IN A QUART,4
60 DATA END,END
100 READ Q$,A$: IF Q$="END" THEN PRINT "YOU ANSWERED";C;"OF THE
QUESTIONS CORRECTLY": PRINT "I HOPE YOU ENJOYED THE QUIZ ": END
110 PRINT Q$;
120 INPUT "??";H$
130 IF H$=A$ THEN PRINT "CORRECT": C=C+1: GO TO 100
140 PRINT "NO, THE ANSWER IS: ";A$: GO TO 100
At the beginning of the
program, the human hasn't answered any questions correctly yet,
so line 5 begins the counter at 0. Each time the human answers a
question correctly, line 130 increases the counter. When the
program ends, line 100 prints the counter, by printing a message
such as:
YOU ANSWERED 2 OF THE QUESTIONS CORRECTLY
It would be nicer to
print ___
YOU ANSWERED 2 OF THE 5 QUESTIONS CORRECTLY
YOUR SCORE IS 40 %
or, if the quiz were changed to include 8 questions:
YOU ANSWERED 2 OF THE 8 QUESTIONS CORRECTLY
YOUR SCORE IS 25 %
To make the computer print such a message, we must make the
computer count how many questions were asked. So we need another
counter. Since we already used C to count the number of correct
answers, let's use Q to count the number of questions asked. Like
C, Q must start at 0; and we must increase Q, by adding 1 each
time another question is asked:
5 C=0: Q=0
10 DATA WHAT'S THE CAPITAL OF NEVADA,CARSON CITY
20 DATA WHAT'S THE CHEMICAL SYMBOL FOR IRON,FE
30 DATA WHAT WORD MEANS 'BROTHER OR SISTER',SIBLING
40 DATA WHAT WAS BEETHOVEN'S FIRST NAME,LUDWIG
50 DATA HOW MANY CUPS ARE IN A QUART,4
60 DATA END,END
100 READ Q$,A$: IF Q$="END" THEN PRINT "YOU ANSWERED";C;"OF
THE";Q;"QUESTIONS CORRECTLY": PRINT "YOUR SCORE IS";C/Q*100;
"%": PRINT "I HOPE YOU ENJOYED THE QUIZ": END
110 PRINT Q$;
115 Q=Q+1
120 INPUT "??";H$
130 IF H$=A$ THEN PRINT "CORRECT": C=C+1: GO TO 100
140 PRINT "NO, THE ANSWER IS: ";A$: GO TO 100
Summing
Let's make the computer imitate an adding machine, so a run
looks like this:
RUN
NOW THE SUM IS 0
WHAT NUMBER DO YOU WANT TO ADD TO THE SUM? 5
NOW THE SUM IS 5
WHAT NUMBER DO YOU WANT TO ADD TO THE SUM? 3
NOW THE SUM IS 8
WHAT NUMBER DO YOU WANT TO ADD TO THE SUM? 6.1
NOW THE SUM IS 14.1
WHAT NUMBER DO YOU WANT TO ADD TO THE SUM? -10
NOW THE SUM IS 4.1
etc.
Here's the program:
10 S=0
20 PRINT "NOW THE SUM IS";S
30 INPUT "WHAT NUMBER DO YOU WANT TO ADD TO THE SUM";X
40 S=S+X
50 GO TO 20
Line 10 starts the sum at 0. Line 20 prints the sum. Line 30
asks the human what number to add to the sum; the human's number
is called X. Line 40 adds X to the sum, so the sum changes. Line
50 makes the computer go to line 20, which prints the new sum.
Lines 20-50 form an infinite loop, which you must abort.
Here's the general procedure for making the computer find a
sum:
1. Start S at 0.
2. Use S. (For example, tell the computer to PRINT S.)
3. Find out what number to add to S. (For example, let the human
input an X.)
4. Increase S, by saying S = S + the number to be added.
5. GO back TO step 2.
Checking account
If your bank's nasty, it charges you 10¢ to process each good
check that you write, and a $5 penalty for each check that
bounces; and it pays no interest on the money you've deposited.
This program makes the computer imitate such a bank. . . .
Start the sum at 0:10 S=0
Chat with the human:20 PRINT "YOUR CHECKING ACCOUNT CONTAINS";S
30 INPUT "DEPOSIT OR WITHDRAW";A$
40 IF A$="DEPOSIT" THEN GO TO 100
50 IF A$="WITHDRAW" THEN GO TO 200
60 PRINT "PLEASE SAY DEPOSIT OR WITHDRAW": GO TO 30
Deposit some money:100 INPUT "HOW MUCH DO YOU WANT TO DEPOSIT";D
110 S=S+D
120 GO TO 20
Withdraw some money:200 INPUT "HOW MUCH DO YOU WANT TO
WITHDRAW";W
210 W=W+.10
220 IF W<=S THEN PRINT "OKAY": S=S-W: GO TO 20
230 PRINT "THAT CHECK BOUNCED": S=S-5: GO TO 20
In that program, the total amount of money in the checking
account is called the sum. Line 10 starts that sum at 0. Line 20
prints the sum. Line 30 asks whether the human wants to deposit
or withdraw.
If the human says DEPOSIT, the computer goes from line 40 to
line 100 (which asks how much to deposit), then to line 110
(which adds the deposit to the sum in the account), then back to
line 20 (for the next transaction).
But if the human says WITHDRAW instead of DEPOSIT, the computer
goes from line 50 to line 200 (which asks how much to withdraw),
then to line 210 (which adds the 10¢ service charge to the
withdrawal amount). Then the computer reaches line 220, which
checks whether the sum S in the account is large enough to cover
the withdrawal (W). If W<=S, the computer says OKAY and processes
the check, by subtracting W from the sum in the account. If W>S
instead, the computer says THAT CHECK BOUNCED and decreases the
sum in the account by the $5 penalty.
How the program is nasty That program is nasty to customers.
For example, suppose you have $1 in your account, and you try to
write a check for 95¢. Since 95¢ + the 10¢ service charge =
$1.05, which is more than you have in your account, your check
will bounce, and you'll be penalized $5. That makes your balance
will become negative $4, and the bank will demand that you pay
the bank $4 ___ just because you wrote a check for 95¢!
Another nuisance is when you leave town permanently and want to
close your account. If your account contains $1, you can't get
your dollar back! The most you can withdraw is 90¢, because 90¢ +
the 10¢ service charge = $1.
That nasty program makes customers hate the bank ___ and hate
the computer!
How to stop the nastiness The bank should make the program
friendlier. Here's how.
To stop accusing the customer of owing money, the bank should
change any negative sum to 0:
15 IF S<0 THEN S=0
To make sure the computer goes to that line, the bank's program
should say GO TO 15 instead of GO TO 20; so the bank should
change line 230 to this:
230 PRINT "THAT CHECK BOUNCED": S=S-5: GO TO 15
Also, to be friendly, the bank should ignore the 10¢ service
charge when deciding whether a check will clear. So the bank
should eliminate line 210. On the other hand, if the check does
clear, the bank should impose the 10¢ service charge afterwards,
like this:
220 IF W<=S THEN PRINT "OKAY": S=S-W-.10: GO TO 15
So if the bank is kind, it will insert line 15, use the new
version of line 230, eliminate line 210, and use the new version
of line 220.
But some banks complain that those changes are too kind! For
example, if a customer whose account contains just 1¢ writes a
million-dollar check (which bounces), the new program charges him
just 1¢ for the bad check; $5 might be more reasonable.
Moral: the hardest thing about programming is choosing your
goal ___ deciding what you want the computer to do.
Series
Let's make the computer add together all the numbers from 7 to
100, so that the computer finds the sum of this series:
7+8+9+...+100. Here's how.
Start the Sum at 0: 10 S=0
Make I go from 7 to 100:20 FOR I = 7 TO 100
Increase the Sum, by adding each I to it:30 S=S+I
40 NEXT
Print the final Sum (which is 5029):50 PRINT S
Let's make the computer add together the squares of all the
numbers from 7 to 100, so that the computer finds the sum of this
series: (7 squared) + (8 squared) + (9 squared) + . . . + (100
squared). Here's how:
10 S=0
20 FOR I = 7 TO 100
30 S=S+I*I
40 NEXT
50 PRINT S
It's the same as the previous program, except that line 30 says
to add I*I instead of I. Line 50 prints the final sum, which is
338259.
Data sums
This program
adds together the numbers in the data:
10 S=0
20 DATA 5, 3, 6.1, etc.
30 DATA etc.
40 DATA etc.
50 DATA 0
60 READ X: IF X=0 THEN PRINT S: END
70 S=S+X
80 GO TO 60
Line 10
starts the sum at 0. Lines 20-40 contain the numbers to be added.
The zero in line 50 is an end mark.
Line 60
reads an X from the data. If X=0, the end of the data's been
reached, so we want the computer to print the sum (S) and end.
But if the X it reads is not zero, the computer proceeds from
line 60 to line 70, adds X to the sum, and goes from line 80 to
line 60, which reads another X.